/*
 * ========================================================
 * Copyright(c) 2014 杭州偶尔科技-版权所有
 * ========================================================
 * 本软件由杭州偶尔科技所有, 未经书面许可, 任何单位和个人不得以
 * 任何形式复制代码的部分或全部, 并以任何形式传播。
 * 公司网址
 *
 * 			http://www.kkkd.com/
 *
 * ========================================================
 */
package com.simon.mengkou.ui.fragment;

import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.StringRes;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.ouertech.android.agm.lib.base.future.core.AgnettyFuture;
import com.ouertech.android.agm.lib.base.future.core.AgnettyResult;
import com.ouertech.android.agm.lib.base.utils.UtilList;
import com.ouertech.android.agm.lib.base.utils.UtilLog;
import com.ouertech.android.agm.lib.base.utils.UtilString;
import com.ouertech.android.agm.lib.ui.base.BaseUIFragment;
import com.ouertech.android.agm.lib.ui.base.FragmentTab;
import com.ouertech.android.agm.lib.ui.base.FragmentTabAdapter;
import com.ouertech.android.agm.lib.ui.base.defaults.fragment.BaseFullFragment;
import com.ouertech.android.agm.lib.ui.base.defaults.fragment.BaseTopFragment;
import com.simon.mengkou.R;
import com.simon.mengkou.data.bean.base.Address;
import com.simon.mengkou.data.bean.base.Category;
import com.simon.mengkou.data.bean.base.Discovery;
import com.simon.mengkou.data.bean.base.GoodTopic;
import com.simon.mengkou.data.bean.base.Image;
import com.simon.mengkou.data.bean.base.Product;
import com.simon.mengkou.data.enums.EDirection;
import com.simon.mengkou.future.base.OuerFutureListener;
import com.simon.mengkou.system.constant.CstOuer;
import com.simon.mengkou.system.global.OuerApplication;
import com.simon.mengkou.system.global.OuerDispatcher;
import com.simon.mengkou.ui.activity.CategoryAdapter;
import com.simon.mengkou.ui.adapter.DiscoveryAdapter;
import com.simon.mengkou.ui.adapter.GoodsTopicListAdapter;
import com.simon.mengkou.ui.view.CustomViewPager;
import com.simon.mengkou.ui.view.HorizontalListView;
import com.simon.mengkou.utils.UtilOuer;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * @author : Zhenshui.Xia
 * @since : 2016/2/29.
 * desc    : 购买界面
 */
public class CategoryFragment extends BaseFullFragment
        implements PullToRefreshBase.OnRefreshListener2<ListView>{

    @Bind(R.id.common_pulltorefresh_id_list)
    PullToRefreshListView mPtrView;
    //推荐商品
    SimpleDraweeView mSdvProduct;
    LinearLayout mLlGrRoot;
    TextView mTvTitle;
    TextView mTvTitleExt;
    TextView mTvPrice;
    TextView mTvMarketPrice;

//    HorizontalListView mHlvCategory;

   // private CategoryAdapter mCategoryAdapter;
    private GoodsTopicListAdapter mAdapter;
    private int mPage = 0;
    private Product mProduct;



    @Override
    protected void initLayout() {
        setContentView(R.layout.layout_common_pulltorefresh_list);
    }

    @Override
    protected void initViews() {
        ButterKnife.bind(this, getView());


        View header = LayoutInflater.from(mActivity).inflate(R.layout.layout_category_header, null);
        mPtrView.getRefreshableView().addHeaderView(header);

        //推荐商品
        mLlGrRoot = (LinearLayout)header.findViewById(R.id.category_id_gr_root);
        mSdvProduct = (SimpleDraweeView) header.findViewById(R.id.category_id_image);
        mLlGrRoot.setOnClickListener(this);
        mTvMarketPrice = (TextView) header.findViewById(R.id.category_id_market_price);
        mTvPrice = (TextView)header.findViewById(R.id.category_id_price);
        mTvTitle = (TextView)header.findViewById(R.id.category_id_title);
        mTvTitleExt = (TextView)header.findViewById(R.id.category_id_title_ext);

        //分类
//        mHlvCategory = (HorizontalListView) header.findViewById(R.id.category_id_list);
//        mCategoryAdapter = new CategoryAdapter(mActivity);
//        mHlvCategory.setAdapter(mCategoryAdapter);
//        mHlvCategory.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                Category data = mCategoryAdapter.getItem(position);
//                OuerDispatcher.presentProductListActivity(mActivity, data.getId(), data.getName());
//            }
//        });

        mPtrView.setOnRefreshListener(this);
        mPtrView.setMode(PullToRefreshBase.Mode.DISABLED);
        mPtrView.setTag(false);

        mAdapter = new GoodsTopicListAdapter(mActivity);
        mPtrView.setAdapter(mAdapter);

        //首次失败重试
        setOnRetryListener(new OnRetryListener() {
            @Override
            public void onRetry() {
                goodsRecommend();
                //getCategory();
                getData(0, EDirection.REFRESH);
            }
        });

        //获取数据
        goodsRecommend();
        //getCategory();
        getData(0, EDirection.REFRESH);
    }


    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        //下拉刷新
        getData(0, EDirection.REFRESH);
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        //上拉加载更多
        getData(mPage + 1, EDirection.LOADMORE);
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.category_id_gr_root://打开商品详情
                if(mProduct != null) {
                    OuerDispatcher.presentProductDetailActivity(mActivity, mProduct.getId());
                }
                break;
        }
    }

    /**
     * 推荐商品
     */
    private void goodsRecommend() {
        AgnettyFuture future = OuerApplication.mOuerFuture.goodsRecommend(
                new OuerFutureListener(mActivity) {

                    @Override
                    public void onComplete(AgnettyResult result) {
                        super.onComplete(result);
                        mProduct = (Product) result.getAttach();
                        if(mProduct != null) {
                            Image image = mProduct.getImageArray().get(0);
//                            if(image.getHeight() != 0 && image.getWidth() != 0) {
//                                mSdvProduct.setAspectRatio(image.getWidth() * 1f / image.getHeight());
//                            }

                            OuerApplication.mImageLoader.loadImage(mSdvProduct, image.getUrl());

                            mTvTitleExt.setText(mProduct.getTitleExt());
                            //商品标题
                            mTvTitle.setText(mProduct.getTitle());
                            //原价
                            mTvMarketPrice.setText(mContext.getString(R.string.buy_recommend_market_price,
                                    UtilOuer.formatPrice(mProduct.getMarketPrice())));

                            mTvMarketPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG );//中划线
                            mTvMarketPrice.getPaint().setAntiAlias(true);
                            //现价
                            mTvPrice.setText(mContext.getString(R.string.buy_recommend_price,
                                    UtilOuer.formatPrice(mProduct.getPrice())));
                            mLlGrRoot.setVisibility(View.VISIBLE);
                        } else {
                            mLlGrRoot.setVisibility(View.GONE);
                        }
                     }

                    @Override
                    public void onNetUnavaiable(AgnettyResult result) {

                    }
                }
        );

        attachDestroyFutures(future);
    }

    /**
     * 获取购买分类
     */
//    private void getCategory() {
//        AgnettyFuture future = OuerApplication.mOuerFuture.buyCategory(
//                new OuerFutureListener(mActivity) {
//
//                    @Override
//                    public void onComplete(AgnettyResult result) {
//                        super.onComplete(result);
//                        List<Category> categories = (List<Category>) result.getAttach();
//                        if(UtilList.isNotEmpty(categories)) {
//                            mHlvCategory.setVisibility(View.VISIBLE);
//                            mCategoryAdapter.setList(categories);
//                        } else {
//                            mHlvCategory.setVisibility(View.GONE);
//                        }
//                    }
//
//                    @Override
//                    public void onNetUnavaiable(AgnettyResult result) {
//
//                    }
//                }
//        );
//
//        attachDestroyFutures(future);
//    }


    private void getData(int page, final int direction) {
        //调用商品搜索接口
        AgnettyFuture future = OuerApplication.mOuerFuture.goodsTopicList(
                page, CstOuer.PAGE.DEFAULT_SIZE,
                new OuerFutureListener(mActivity){

                    public void onStart(AgnettyResult result) {
                        boolean flag = (Boolean)mPtrView.getTag();
                        if(!flag) {
                            setLoading(true);
                        }
                    }

                    @Override
                    public void onComplete(AgnettyResult result) {
                        super.onComplete(result);
                        boolean flag = (Boolean)mPtrView.getTag();
                        if(!flag) {
                            mPtrView.setTag(true);
                            setLoading(false);
                        } else {
                            mPtrView.onRefreshComplete();
                        }

                        List<GoodTopic> datas = (List<GoodTopic>) result.getAttach();


                        if(direction == EDirection.REFRESH) {
                            mPage = 0;

                            if(UtilList.isEmpty(datas)) {
                                mPtrView.setMode(PullToRefreshBase.Mode.DISABLED);
                                mAdapter.clearAll();
                            } else {
                                if(UtilList.getCount(datas) < CstOuer.PAGE.DEFAULT_SIZE) {
                                    mPtrView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                                } else {
                                    mPtrView.setMode(PullToRefreshBase.Mode.BOTH);
                                }

                                mAdapter.setList(datas);
                            }
                        } else {
                            if(UtilList.getCount(datas) < CstOuer.PAGE.DEFAULT_SIZE) {
                                mPtrView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                            }

                            mPage++;
                            mAdapter.addList(datas);
                        }
                    }

                    public void onNetUnavaiable(AgnettyResult result) {
                        super.onNetUnavaiable(result);
                        boolean flag = (Boolean)mPtrView.getTag();
                        if(!flag) {
                            setRetry(true);
                        } else {
                            mPtrView.onRefreshComplete();
                        }
                    }

                    @Override
                    public void onException(AgnettyResult result) {
                        super.onException(result);
                        boolean flag = (Boolean)mPtrView.getTag();
                        if(!flag) {
                            setRetry(true);
                        } else {
                            mPtrView.onRefreshComplete();
                        }
                    }
                });

        attachDestroyFutures(future);
    }
}
